<template>
  <div class="main">
    <Search :initData="initSearchData" @emitSearchData="getSearchData"></Search>
    <div class="content">
      <a-row :gutter="[16, 16]">
        <PieAndLine :pieAndLineData="statisticsTypePieAndLineData"></PieAndLine>
      </a-row>
      <a-row :gutter="[16, 16]">
        <PieAndLine
          :pieAndLineData="statisticsReasonPieAndLineData"
        ></PieAndLine>
      </a-row>
      <a-row :gutter="[16, 16]">
        <PieAndLine
          :pieAndLineData="statisticsResultPieAndLineData"
        ></PieAndLine>
      </a-row>
      <a-row :gutter="[16, 16]" style="position: relative;">
        <InfoList :infoData="infoData"></InfoList>
        <LineChart :span="24" :lineData="orderLineData"></LineChart>
      </a-row>
    </div>
  </div>
</template>

<script>
import Moment from "moment";
import PieAndLine from "@/components/echart/pieAndLine";
import PieChart from "@/components/echart/pie";
import LineChart from "@/components/echart/line";
import { themeOption } from "@/components/echart/buildEChartOption";
import InfoList from "./components/infoList";
import Search from "@/components/search/statisticsSearch";
import { buildDateAxis } from "@/unit/tool";
import api from "@/server/userConfig";

function transformTimeArray(lists) {
  return lists.map((item, index) => {
    return {
      value: [item.time, item.number]
    };
  });
}

function buildPieLists(object, titleStr) {
  let lists = [{ option: {}, data: [] }];
  let dataLists = [];
  let legendData = [];
  let showCount = 10;
  for (const key in object) {
    if (object.hasOwnProperty(key)) {
      dataLists.push({
        name: key,
        value: object[key].number
      });
    }
  }

  dataLists = dataLists
    .sort((a, b) => {
      return b.value - a.value;
    })
    .slice(0, showCount);

  lists[0].option = {
    radius: "120",
    center: ["240", "180"],
    label: {
      position: "inner",
      formatter: function(e) {
        let newValue = Math.ceil(parseFloat(e.percent));
        if (newValue >= 5) {
          return newValue + "%";
        } else {
          return "";
        }
        // return Math.ceil(parseFloat(e.percent)) + "%";
      }
    }
  };

  legendData = dataLists.map((item, index) => {
    let name = item.name == "" ? "未知字段" : item.name;
    // selected[name] = index < showCount ? true : false;
    return name;
  });

  lists[0].data = dataLists;

  return {
    title: {
      text: titleStr,
      left: "16",
      top: "24",
      textStyle: {
        fontSize: 18,
        fontWeight: 600,
        color: "#1890FF"
      }
    },
    legend: {
      orient: "vertical",
      left: "400",
      top: "60",
      icon: "circle",
      data: legendData,
      // selected: selected,
      textStyle: {
        fontSize: 12,
        fontWeight: 200,
        color: "#000000"
      },
      formatter: params => {
        let str = "";
        dataLists.forEach((itme, index) => {
          if (params == itme.name) {
            str = `${itme.name} : ${itme.value}`;
          }
          return false;
        });

        return str;
      }
    },
    dataLists: lists
  };
}

function buildLineLists(object, option, pieLists) {
  let { startTime, endTime, timeFormat } = option;
  let lineDataLists = [];
  let legendData = [];
  let xAxisData = buildDateAxis({ timeFormat, startTime, endTime });
  if (pieLists && pieLists.length) {
    pieLists.forEach((itme, index) => {
      let key = itme.name;
      if (object.hasOwnProperty(key)) {
        lineDataLists.push({
          option: {
            name: key
          },
          data: transformTimeArray(object[key])
        });
      }
    });
  } else {
    for (const key in object) {
      if (object.hasOwnProperty(key)) {
        lineDataLists.push({
          option: {
            name: key,
            symbolSize: 10
          },
          data: transformTimeArray(object[key])
        });
      }
    }
  }

  if (pieLists && pieLists.length) {
    legendData = pieLists.map((item, index) => {
      let name = item.name;
      // selected[name] = index < showCount ? true : false;
      return name;
    });
  }

  return {
    xAxis: {
      type: "category",
      data: xAxisData
    },
    lineDataLists
  };
}

function buildOrderLineLists(object, option, pieLists) {
  let obj = buildLineLists(object, option, pieLists);
  return {
    title: {
      text: "重大故障",
      left: "16",
      top: "24",
      textStyle: {
        fontSize: 18,
        fontWeight: 600,
        color: "#1890FF"
      }
    },
    legend: {
      orient: "horizontal",
      left: "600",
      top: "20"
    },
    grid: { left: 600, width: "50%" },
    ...obj
  };
}

function buildPieAndLineLists(pieData, lineData, parames, item) {
  let pieSeriesLists = [{ option: {}, data: [] }];
  // 标题
  let titleStr = item.type;
  // 过滤后的饼图数据项
  let pieDataLists = [];
  // 过滤后的折线图数据项
  let lineDataLists = [];
  // legend数据
  let legendData = [];
  // x轴
  let xAxisData = [];
  // 控制显示的项目数
  let showCount = 10;

  // 时间参数
  let startTime = parames.startTime;
  let endTime = parames.endTime;
  let timeFormat = parames.timeType == "今年" ? "months" : "days";

  for (const key in pieData) {
    if (pieData.hasOwnProperty(key)) {
      pieDataLists.push({
        name: key,
        value: pieData[key].number
      });
    }
  }

  pieDataLists = pieDataLists
    .sort((a, b) => {
      return b.value - a.value;
    })
    .slice(0, showCount);

  pieSeriesLists[0].option = {
    radius: "120",
    center: ["240", "180"],
    label: {
      position: "inner",
      formatter: function(e) {
        let newValue = Math.ceil(parseFloat(e.percent));
        if (newValue >= 5) {
          return newValue + "%";
        } else {
          return "";
        }
        // return Math.ceil(parseFloat(e.percent)) + "%";
      }
    }
  };

  pieSeriesLists[0].data = pieDataLists;

  legendData = pieDataLists.map((item, index) => {
    let name = item.name == "" ? "未知字段" : item.name;
    return name;
  });

  xAxisData = buildDateAxis({ timeFormat, startTime, endTime });

  pieDataLists.forEach((itme, index) => {
    let key = itme.name;
    if (lineData.hasOwnProperty(key)) {
      lineDataLists.push({
        option: {
          name: key,
          symbolSize: 10
        },
        data: transformTimeArray(lineData[key])
      });
    }
  });

  return {
    title: {
      text: titleStr,
      left: "16",
      top: "24",
      textStyle: {
        fontSize: 18,
        fontWeight: 600,
        color: "#1890FF"
      }
    },
    legend: {
      orient: "vertical",
      left: "400",
      top: "60",
      icon: "circle",
      data: legendData,
      textStyle: {
        fontSize: 12,
        fontWeight: 200,
        color: "#000000"
      },
      formatter: params => {
        let str = "";
        pieDataLists.forEach((itme, index) => {
          if (params == itme.name) {
            str = `${itme.name} : ${itme.value}`;
          }
          return false;
        });

        return str;
      }
    },
    xAxis: {
      type: "category",
      // axisLabel: {
      //   formatter: (value, index) => {
      //     let texts = Moment(value).format("YYYY-MM");
      //     return texts;
      //   }
      // },
      data: xAxisData
    },
    grid: {
      left: 600,
      width: "50%"
    },
    pieSeriesLists,
    lineDataLists
  };
}

export default {
  name: "ServiceStatistics",
  components: {
    Search,
    PieChart,
    LineChart,
    PieAndLine,
    InfoList
  },
  data() {
    return {
      initSearchData: {
        districtValue: "全部",
        timeType: "今年",
        endTime: `${this.$Moment()
          .endOf("year")
          .format("YYYY-MM-DD")} 23:59:59`,
        startTime: `${this.$Moment()
          .startOf("year")
          .format("YYYY-MM-DD")} 00:00:00`
      },
      failureLists: [
        {
          type: "故障类型",
          key: "statisticsTypePieAndLineData"
        },
        {
          type: "故障原因",
          key: "statisticsReasonPieAndLineData"
        },
        {
          type: "故障处理结果",
          key: "statisticsResultPieAndLineData"
        }
      ],
      infoData: [],
      orderLineData: {},
      statisticsTypePieAndLineData: {},
      statisticsReasonPieAndLineData: {},
      statisticsResultPieAndLineData: {}
    };
  },
  methods: {
    async getStatisticsPieChart(parames, key) {
      const res = await api.statisticsPieChart({
        ownDistrict: parames.ownDistrict,
        startTime: parames.startTime,
        endTime: parames.endTime,
        statisticsType: parames.statisticsType
      });
      console.log(res);

      if (res.MsgCode !== 0) {
        return;
      }

      this[key] = buildPieLists(res.Data);

      console.log(this[key]);
    },

    async getStatisticsLineChart(parames, key) {
      const res = await api.statisticsLineChart({
        ownDistrict: parames.ownDistrict,
        startTime: parames.startTime,
        endTime: parames.endTime,
        statisticsType: parames.statisticsType,
        timeType: parames.timeType == "今年" ? "一年" : ""
      });

      if (res.MsgCode !== 0) {
        return;
      }

      this[key] = buildLineLists(res.Data, {
        startTime: parames.startTime,
        endTime: parames.endTime,
        timeFormat: parames.timeType == "今年" ? "months" : "days"
      });
    },

    async getViIssueOrderInfo(parames, key) {
      const res = await api.viIssueOrderInfo({
        ownDistrict: parames.ownDistrict,
        startTime: parames.startTime,
        endTime: parames.endTime,
        user: this.userName
      });

      if (res.MsgCode !== 0) {
        return;
      }

      this[key] = res.Data;
    },

    async getOrderLineChart(parames, key) {
      const res = await api.orderLineChart({
        ownDistrict: parames.ownDistrict,
        startTime: parames.startTime,
        endTime: parames.endTime,
        statisticsType: parames.statisticsType,
        timeType: parames.timeType == "今年" ? "一年" : ""
      });

      if (res.MsgCode !== 0) {
        return;
      }

      this[key] = buildOrderLineLists(res.Data, {
        startTime: parames.startTime,
        endTime: parames.endTime,
        timeFormat: parames.timeType == "今年" ? "months" : "days"
      });
    },

    async getPieAndLineData(parames, item) {
      const pieRes = await api.statisticsPieChart({
        ownDistrict: parames.districtValue,
        startTime: parames.startTime,
        endTime: parames.endTime,
        statisticsType: item.type
      });

      if (pieRes.MsgCode !== 0) {
        // ${parames.timeType}
        this.$message.warning(`${item.type}暂无数据`);
        return;
      }

      const lineRes = await api.statisticsLineChart({
        ownDistrict: parames.districtValue,
        startTime: parames.startTime,
        endTime: parames.endTime,
        statisticsType: item.type,
        timeType: parames.timeType == "今年" ? "一年" : ""
      });

      if (lineRes.MsgCode !== 0) {
        this.$message.warning(`${item.type}暂无数据`);
        return;
      }

      let key = item.key;
      this[key] = buildPieAndLineLists(
        pieRes.Data,
        lineRes.Data,
        parames,
        item
      );
    },

    getData(parames) {
      this.failureLists.forEach((item, index) => {
        this.getPieAndLineData(parames, item);
      });

      this.getViIssueOrderInfo(
        {
          ownDistrict: parames.districtValue,
          startTime: parames.startTime,
          endTime: parames.endTime,
          timeType: parames.timeType
        },
        "infoData"
      );

      this.getOrderLineChart(
        {
          ownDistrict: parames.districtValue,
          startTime: parames.startTime,
          endTime: parames.endTime,
          timeType: parames.timeType
        },
        "orderLineData"
      );
    },

    getSearchData(value) {
      this.getData(value);
    },

    getLocalStorageData() {
      const phone = localStorage.getItem("phone");
      this.userName = phone;
      if (!phone) {
        this.$router.push("/login");
      }
    },
    callback(key) {}
  },

  created() {
    this.getLocalStorageData();
  },

  mounted() {
    this.getData(this.initSearchData);
  }
};
</script>

<style scoped="scoped">
.main {
  height: 100%;
  width: 100%;
}

.main > .content {
  padding: 16px;
  background: #ecf2f7;
}
</style>
